/**
 * 限额穿透报表
 */
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { message } from 'antd';
import accounting from 'accounting';
import { DATA_ENTRY, AdvancedSearch, ModalC, ContentPackage, TableC, PrimaryC } from '../../../comps';
import myStyle from './index.less';
import MyModal from '../../InvestmentMonitor/LimitMonitoring/myModal';
import _, { isBoolean } from 'lodash';
import moment from 'moment';
import { findTitleByValue } from '../../../utils/utils';
import uuid from 'es6-uuid';
const statisticsType = [
  { value: 'ZCGLJH', title: '资产管理计划' },
  { value: 'WW', title: '委外投资' },
  { value: 'SMJJ', title: '私募基金' },
];
const isBooleanArr = [
  { value: '0', title: '是' },
  { value: '1', title: '否' },
];
@Form.create()
@connect(({ limitThroughReportM, loading }) => ({
  limitThroughReportM,
  tableLoading: loading.effects['limitThroughReportM/getTableData'],
  loading,
}))
export default class Index extends PureComponent {
  state = {
    dataSource: [],
    columns: [],
    visible: false, //模态框显示与否
    searchForm: { isPassThrough: '1' }, //搜索条件
    productCodeList: [],
    isReset: false, // 是否重置
    previewDate: undefined,
    isShowLog: false, //数据日志弹窗是否显示
    logData: {}, //数据日志数据
    logColumns: [
      { key: 'expirationDate', title: '报表日期' },
      { key: 'tradeType', title: '资产类型' },
      { key: 'tradingCode', title: '证券代码' },
      { key: 'tradingName', title: '证券全称' },
      { key: 'isValuation', title: '是否提供当日估值解析' },
      { key: 'valuationDate', title: '最新估值表数据日期' },
    ],
  };

  componentDidMount() {
    // 查询 T-1 日期
    this.getPreviousData();
  }
  // 查询T-1 交易日
  getPreviousData = () => {
    this.props.dispatch({
      type: 'limitThroughReportM/getPreviewDay',
      payload: {
        date: moment().format('YYYY-MM-DD'),
        tenant: localStorage.getItem('antd-pro-tenant'),
      },
      callback: (msg, date) => {
        if (msg == 'success') {
          this.setState(
            {
              previewDate: moment(date).format('YYYY-MM-DD'),
            },
            () => {
              this.queryTableList();
              // 截止时间赋初值
              this.searchRef?.props.form.setFieldsValue({
                expirationDate: moment(date),
              });
            },
          );
        }
      },
    });
  };
  //查询表格数据
  queryTableList = () => {
    const { searchForm, currentPage, numInPage, previewDate } = this.state;
    const { dispatch } = this.props;
    dispatch({
      type: 'limitThroughReportM/getTableData',
      payload: {
        tenant: localStorage.getItem('antd-pro-tenant'),
        currentPage: 1,
        numInPage: 9999,
        expirationDate: previewDate,
        ...searchForm,
      },
      callback: (msg, _data) => {
        if (msg == 'success') {
          this.setState({
            dataSource: _data?.dataSource || [],
            columns: _data?.columns || [],
          });
        } else {
          this.setState({
            dataSource: [],
            columns: _data?.columns || [],
          });
        }
      },
    });
  };

  //展示表格
  showTable = () => {
    const { columns = [], dataSource = [] } = this.state;
    const { tableLoading } = this.props;
    const currentHeight = document.getElementById('tabDiyWidth') ? document.getElementById('tabDiyWidth').offsetHeight - 250 : '100%';
    const newColumns = _.cloneDeep(columns);
    if (newColumns?.length) {
      newColumns.map((item) => {
        if (item.key != 'ruleNo' && item.key != 'ruleDesc' && item.key != 'operate') {
          item.align = 'right';
          item.width = 150;
          item.render = (text, record) => {
            if (record.pecent === false) {
              return text !== null ? text : '--';
            } else {
              return text !== null ? accounting.formatNumber(Number(text) * 100, 2) + '%' : '--';
            }
          };
        }
        if (item.key == 'ruleDesc') {
          item.width = '45%';
          item.ellipsis = true;
        }
        if (item.key == 'ruleNo') {
          item.width = 120;
        }
      });
      newColumns.push({
        title: '操作',
        key: 'operate',
        width: 55,
        render: (text, record) => {
          return <a onClick={() => this.showInfo(record)}>详细 </a>;
        },
      });
    }
    return (
      <div style={{ marginTop: '20px' }}>
        <TableC loading={tableLoading} columns={newColumns} dataSource={dataSource} hidePage={true} selfScrollY={true} rowKey='ruleNo' />
      </div>
    );
  };
  //查询详情页信息 弹出模态框
  showInfo = (record) => {
    record.expirationDate = moment(this.state.searchForm?.expirationDate || this.state.previewDate).format('YYYY-MM-DD');
    (record.isPassThrough = this.searchRef?.props.form.getFieldValue('isPassThrough')),
      this.setState({
        visible: true,
        rowRecord: record,
        timeStamp: new Date().getTime(),
      });
  };
  // 模态框
  showModal = () => {
    const { rowRecord, visible, timeStamp } = this.state;
    const props = {
      visible: visible,
      onOk: () => {
        this.setState({ visible: false });
      },
      onCancel: () => {
        this.setState({ visible: false });
      },
      title: '限额详情',
      className: 'limitDetail',
      footer: null,
      height: 500,
    };
    return (
      <div>
        <ModalC {...props}>
          <MyModal record={rowRecord} timeStamp={timeStamp} type={'report'} />
        </ModalC>
      </div>
    );
  };
  // 点击查询
  onQuery = (params) => {
    const { productCodeList } = this.state;
    if (params.expirationDate) {
      params.expirationDate = params.expirationDate.format('YYYY-MM-DD');
    }
    if (params?.productCodeList?.length) {
      params.productCodeList = productCodeList;
    }
    this.setState(
      {
        isReset: false,
        currentPage: 1,
        searchForm: {
          ...params,
        },
      },
      () => {
        this.queryTableList();
      },
    );
  };
  // 点击重置
  onClear = () => {
    this.setState({
      isReset: true,
      productCodeList: [],
    });
    if (this.state.previewDate) {
      this.searchRef?.props.form.setFieldsValue({
        expirationDate: moment(this.state.previewDate),
      });
    }
  };
  // 选中产品
  productOnChange = (e) => {
    //取产品的code 传给后台
    if (!e) {
      this.setState({
        productCodeList: [],
      });
      return;
    }
    const arr = e.info.map((item) => {
      return item.portfolioCode;
    });
    this.setState({
      productCodeList: arr || [],
    });
  };
  //展示数据日志弹窗
  showLog = () => {
    this.queryLogList(); //查询数据日志
    this.setState({
      isShowLog: true,
    });
  };
  //查询日志列表
  queryLogList = () => {
    this.props.dispatch({
      type: 'limitThroughReportM/queryLogList',
      payload: {
        expirationDate: moment(this.state.searchForm?.expirationDate || this.state.previewDate).format('YYYY-MM-DD'),
      },
      callback: (data) => {
        if (data) {
          data?.dataSource?.map((item) => {
            item.id = uuid(16);
          });
        }
        this.setState({
          logData: data || {},
        });
      },
    });
  };
  //展示数据日志弹窗
  showModalLog = () => {
    const { isShowLog, logData, searchForm } = this.state;
    const props = {
      visible: isShowLog,
      onOk: () => {
        this.setState({ isShowLog: false });
      },
      onCancel: () => {
        this.setState({ isShowLog: false });
      },
      title: '数据日志',
      footer: null,
      height: 500,
    };
    let date = searchForm.expirationDate ? moment(searchForm.expirationDate) : this.searchRef.props.form.getFieldValue('expirationDate');
    return (
      <div>
        <ModalC {...props}>
          <div>
            <div>跑批结束时间：{logData.runEndDateTime ? moment(logData.runEndDateTime).format('YYYY-MM-DD HH:mm:ss') : '--'}</div>
            {logData.statistics &&
              logData.statistics.map((item, key) => {
                return (
                  <div key={key} style={{ lineHeight: '24px' }}>
                    {date?.format('YYYY-MM-DD')}日存续{findTitleByValue(item.type, statisticsType)}共{item.count || 0}只，当日估值解析已导入{item.successCount || 0}只，尚未导入
                    {item.failCount || 0}只。
                  </div>
                );
              })}
            {this.showLogTable()}
          </div>
        </ModalC>
      </div>
    );
  };
  //查询表格数据
  queryTableList = () => {
    const { searchForm, currentPage, numInPage, previewDate } = this.state;
    const { dispatch } = this.props;
    dispatch({
      type: 'limitThroughReportM/getTableData',
      payload: {
        tenant: localStorage.getItem('antd-pro-tenant'),
        currentPage: 1,
        numInPage: 999,
        expirationDate: previewDate,
        ...searchForm,
      },
      callback: (msg, _data) => {
        if (msg == 'success') {
          this.setState({
            dataSource: _data?.dataSource || [],
            columns: _data?.columns || [],
          });
        } else {
          this.setState({
            dataSource: [],
            columns: _data?.columns || [],
          });
        }
      },
    });
  };
  //数据日志表格
  showLogTable = () => {
    const { loading } = this.props;
    const { logColumns = [], logData } = this.state;
    logColumns.map((item) => {
      if (item.key == 'tradeType') {
        item.render = (text) => {
          return findTitleByValue(text, statisticsType);
        };
      }
      if (item.key == 'isValuation') {
        item.render = (text) => {
          return findTitleByValue(text, isBooleanArr);
        };
      }
    });
    return (
      <div style={{ marginTop: '20px' }}>
        <TableC
          loading={loading.effects['limitThroughReportM/queryLogList'] == true}
          columns={logColumns}
          dataSource={logData.dataSource || []}
          hidePage={true}
          scroll={{ y: 300 }}
          rowKey='id'
        />
      </div>
    );
  };
  render() {
    const searchProps = {
      dataSource: [
        {
          dataIndex: 'productCodeList',
          title: '产品',
          type: DATA_ENTRY.PRODUCTLIST,
          multiple: true,
          onChange: this.productOnChange,
        },
        {
          dataIndex: 'expirationDate',
          title: '截止日期',
          type: DATA_ENTRY.SINGLEDATE,
          allowClear: false,
          disableEnd: this.state.previewDate ? moment(this.state.previewDate).add(1, 'days') : undefined,
        },
        {
          dataIndex: 'isPassThrough',
          title: '是否穿透',
          type: DATA_ENTRY.SELECT,
          isTrueFalseJudge: true,
          initialValue: '1',
        },
      ],
      onQuery: this.onQuery,
      onClear: this.onClear,
      onRef: (ref) => (this.searchRef = ref),
    };
    return (
      <ContentPackage
        title='限额穿透报表'
        contentHtml={
          <div className={myStyle.LimitReport}>
            <AdvancedSearch {...searchProps} />
            <PrimaryC title='数据日志' disabled={this.state.dataSource?.length == false} onClick={this.showLog} style={{ marginTop: '15px' }} />
            {this.showTable()}
            {this.state.visible && this.showModal()}
            {this.state.isShowLog && this.showModalLog()}
          </div>
        }
      />
    );
  }
}
